package admin

import (
	"context"
	"encoding/json"

	"github.com/google/uuid"
	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// GetLLMProviderModels 获取LLM提供商的所有模型
func (h *AdminHandler) GetLLMProviderModels(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "LLM 提供商ID无效")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "LLM 提供商不存在")
	}

	// 解析模型列表
	var models []entity.ModelInfo
	if provider.Models != nil {
		if err := json.Unmarshal(provider.Models, &models); err != nil {
			return response.InternalServerError(c, "解析模型列表失败")
		}
	}

	return response.Success(c, map[string]interface{}{
		"provider_id": id,
		"rows":        models,
		"total":       len(models),
	})
}

// AddModelToLLMProvider 添加模型到LLM提供商
func (h *AdminHandler) AddModelToLLMProvider(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "LLM 提供商ID无效")
	}

	var req LLMModelInfo
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "请求格式无效")
	}

	// 验证必填字段
	if req.Name == "" {
		return response.BadRequest(c, "模型名称必填")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "LLM 提供商不存在")
	}

	// 解析模型列表
	var models []entity.ModelInfo
	if provider.Models != nil {
		if err := json.Unmarshal(provider.Models, &models); err != nil {
			return response.InternalServerError(c, "解析模型列表失败")
		}
	}

	// 检查模型是否已存在
	for _, model := range models {
		if model.Name == req.Name {
			return response.BadRequest(c, "模型已存在")
		}
	}

	// 添加新模型
	newModel := entity.ModelInfo{
		Name:        req.Name,
		DisplayName: req.DisplayName,
		MaxTokens:   req.MaxTokens,
		InputPrice:  req.InputPrice,
		OutputPrice: req.OutputPrice,
		Description: req.Description,
		IsDefault:   req.IsDefault,
	}

	models = append(models, newModel)

	// 更新数据库
	modelsJSON, err := json.Marshal(models)
	if err != nil {
		return response.InternalServerError(c, "序列化模型列表失败")
	}

	provider.Models = modelsJSON
	if err := h.repos.GetLLMProvider().UpdateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "更新LLM提供商失败")
	}

	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "刷新LLM提供商管理器失败")
		}
	}

	return response.Success(c, newModel)
}

// UpdateLLMProviderModel 更新LLM提供商的特定模型
func (h *AdminHandler) UpdateLLMProviderModel(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "LLM 提供商ID无效")
	}

	modelName := c.Param("model")
	if modelName == "" {
		return response.BadRequest(c, "模型名称必填")
	}

	var req LLMModelInfo
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "请求格式无效")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "LLM 提供商不存在")
	}

	// 解析模型列表
	var models []entity.ModelInfo
	if provider.Models != nil {
		if err := json.Unmarshal(provider.Models, &models); err != nil {
			return response.InternalServerError(c, "解析模型列表失败")
		}
	}

	// 查找并更新模型
	found := false
	for i, model := range models {
		if model.Name == modelName {
			// 更新字段
			if req.DisplayName != "" {
				models[i].DisplayName = req.DisplayName
			}
			if req.MaxTokens > 0 {
				models[i].MaxTokens = req.MaxTokens
			}
			if req.InputPrice >= 0 {
				models[i].InputPrice = req.InputPrice
			}
			if req.OutputPrice >= 0 {
				models[i].OutputPrice = req.OutputPrice
			}
			if req.Description != "" {
				models[i].Description = req.Description
			}
			models[i].IsDefault = req.IsDefault
			found = true
			break
		}
	}

	if !found {
		return response.NotFound(c, "模型不存在")
	}

	modelsJSON, err := json.Marshal(models)
	if err != nil {
		return response.InternalServerError(c, "序列化模型列表失败")
	}

	provider.Models = modelsJSON
	if err := h.repos.GetLLMProvider().UpdateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "更新LLM提供商失败")
	}

	// 刷新provider管理器
	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "刷新LLM提供商管理器失败")
		}
	}

	return response.Success(c, "模型更新成功")
}

// DeleteLLMProviderModel 删除LLM提供商的特定模型
func (h *AdminHandler) DeleteLLMProviderModel(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "LLM 提供商ID无效")
	}

	modelName := c.Param("model")
	if modelName == "" {
		return response.BadRequest(c, "模型名称必填")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "LLM 提供商不存在")
	}

	// 解析现有模型列表
	var models []entity.ModelInfo
	if provider.Models != nil {
		if err := json.Unmarshal(provider.Models, &models); err != nil {
			return response.InternalServerError(c, "解析模型列表失败")
		}
	}

	// 查找并删除模型
	found := false
	for i, model := range models {
		if model.Name == modelName {
			models = append(models[:i], models[i+1:]...)
			found = true
			break
		}
	}

	if !found {
		return response.NotFound(c, "模型不存在")
	}

	// 更新数据库
	modelsJSON, err := json.Marshal(models)
	if err != nil {
		return response.InternalServerError(c, "序列化模型列表失败")
	}

	provider.Models = modelsJSON
	if err := h.repos.GetLLMProvider().UpdateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "更新LLM提供商失败")
	}

	// 刷新provider管理器
	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "刷新LLM提供商管理器失败")
		}
	}

	return response.Success(c, "模型删除成功")
}

// SetLLMProviderModelDefault 设置模型默认状态
func (h *AdminHandler) SetLLMProviderModelDefault(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "LLM 提供商ID无效")
	}

	modelName := c.Param("model")
	if modelName == "" {
		return response.BadRequest(c, "模型名称必填")
	}

	var req struct {
		IsDefault bool `json:"is_default"`
	}
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "请求格式无效")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "LLM 提供商不存在")
	}

	// 解析现有模型列表
	var models []entity.ModelInfo
	if provider.Models != nil {
		if err := json.Unmarshal(provider.Models, &models); err != nil {
			return response.InternalServerError(c, "解析模型列表失败")
		}
	}

	// 查找并更新模型状态
	found := false
	var selectedModel entity.ModelInfo
	for i, model := range models {
		if model.Name == modelName {
			selectedModel = model
			selectedModel.IsDefault = req.IsDefault
			found = true
			models[i] = selectedModel
			break
		}
	}

	if !found {
		return response.NotFound(c, "模型不存在")
	}

	modelsJSON, err := json.Marshal(models)
	if err != nil {
		return response.InternalServerError(c, "序列化模型列表失败")
	}

	provider.Models = modelsJSON
	if err := h.repos.GetLLMProvider().UpdateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "更新LLM提供商失败")
	}

	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "刷新LLM提供商管理器失败")
		}
	}

	return response.Success(c, selectedModel)
}
